//
//  JHCollectionViewCycleImage.m
//  UI16_UICollectionView封装轮播图
//
//  Created by tusm on 16/8/4.
//  Copyright © 2016年 tusm. All rights reserved.
//

#import "JHCollectionViewCycleImage.h"

#define kCollectionViewCellReuse @"Reuse"
@interface JHCollectionViewCell : UICollectionViewCell
@property (nonatomic,strong)UIImageView *cycleImage;
@property (nonatomic,strong)UILabel *cycleLable;
@end






@interface JHCollectionViewCycleImage ()<UICollectionViewDelegate,UICollectionViewDataSource>



//控件
@property (nonatomic,strong)UICollectionView *cycleCollectionView;
@property (nonatomic,strong)UIPageControl *imagePage;
//布局
@property (nonnull,strong)UICollectionViewFlowLayout *flowLayOut;


//设置定时间隔
@property (nonatomic,assign)CGFloat *timeInterval;
//设定定时器对象
@property (nonatomic,strong)NSTimer *cycleTimer;
/** 当前item的下标 */
@property(nonatomic, assign)NSInteger itemIndex;
/** 当前section下标 */
@property(nonatomic, assign)NSInteger currentSection;
//协议方法
- (void)handleDataWithObject:(NSString *)objc cell:(JHCollectionViewCell *)cell;
@end





@implementation JHCollectionViewCycleImage

//- (instancetype)initWithFrame:(CGRect)frame  TimeInterval:(CGFloat)time{
//    self = [super initWithFrame:frame];
//    if (self) {
//        self.backgroundColor = [UIColor redColor];
//        [self setup];
//    }
//    return self;
//}

//sB走以下初始化方法
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.backgroundColor = [UIColor redColor];
        [self setup];
        NSLog(@"+++++++++++++%lf",self.frame.size.width); //此时打印view的宽度为0
        
//        if (time > 0) {
//            self.timeInterval = &(timeInterval);
//        }
        
    }
    return self;

}
//设置
- (void)setup{
    [self createCollectionView];

    [self createPageControl];
    
    [self addTheTimer];
}
- (void)createCollectionView{
//初始化使用下划线
    _flowLayOut = [[UICollectionViewFlowLayout alloc] init];
    _flowLayOut.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _flowLayOut.minimumLineSpacing = 0;
    _flowLayOut.minimumInteritemSpacing = 0;
    
//    _flowLayOut.sectionInset = UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)
    
    _cycleCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_flowLayOut];
    //签订代理,指定代理人,两个协议方法
    _cycleCollectionView.delegate = self;
    _cycleCollectionView.dataSource = self;
    _cycleCollectionView.pagingEnabled = YES;
    _cycleCollectionView.bounces = NO;
    //关闭水平滚动条
    _cycleCollectionView.showsHorizontalScrollIndicator = NO;
    //添加视图
    [self addSubview:_cycleCollectionView];
    [_cycleCollectionView registerClass:[JHCollectionViewCell class] forCellWithReuseIdentifier:kCollectionViewCellReuse];

}
- (void)createPageControl{

    _imagePage = [[UIPageControl alloc] initWithFrame:CGRectZero];
    [self addSubview:_imagePage];
//    _imagePage.backgroundColor = [UIColor redColor];


}

- (void)addTheTimer{
    //创建并添加到loop中
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(changePageByTime) userInfo:nil repeats:YES];
    //需要添加runloop,仅仅是创建并没有添加在loop中
//    NSTimer *timer = [NSTimer timerWithTimeInterval:3 target:self selector:@selector(changePageByTime) userInfo:nil repeats:YES];
   // NSRunLoopCommonModes 和NSunDefaultRunLoopModes
    //后者代表默认状态,scheduledTimer

//    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; //mods代表了
    self.cycleTimer = timer;
    
    //取消

    
    if (_itemIndex == self.array.count) {
        _itemIndex = 0;
        _currentSection++;
    }
    if (self.array.count > 0) {
        //偏移到最新位置(下一张)
        [self.cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_itemIndex inSection:_currentSection] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    }
    if (_itemIndex == 6) {
        _imagePage.currentPage = 1;
    }
    else {
        _imagePage.currentPage = _itemIndex;
    }

    if (_cycleCollectionView.contentOffset.x == 0) {
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_array.count - 2 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    } else if (_cycleCollectionView.contentOffset.x == _cycleCollectionView.bounds.size.width * (_array.count - 1)){
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] atScrollPosition:0 animated:NO];
    }
    
    _itemIndex++;

}



#pragma mark - 两个协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    _imagePage.numberOfPages = _array.count - 2;

    return _array.count;

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    JHCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCollectionViewCellReuse forIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0f green:arc4random()%256/255.0f blue:arc4random()%256/255.0f alpha:1];
    //该位置取出在外赋值
//    [self.delegate handleCell:_array[indexPath.row] cell:cell ];
    cell.cycleImage.image = [UIImage imageNamed:_array[indexPath.row]];
    cell.cycleLable.text = _labelArray[indexPath.row];
    
    return cell;
    
}

#pragma mark - 点击item的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    if (self.delegate) {
        [self.delegate didClickedItemAtIndexPath:indexPath];
    }

}


- (void)layoutSubviews{
    [super layoutSubviews];
    
    NSLog(@"====================%lf",self.frame.size.width); //此时打印view的宽度正确
    _cycleCollectionView.frame = self.bounds;
    _flowLayOut.itemSize = self.bounds.size;
    //设置偏移量
    [_cycleCollectionView setContentOffset:CGPointMake(self.bounds.size.width, 0)];
    _imagePage.frame = CGRectMake(0, 0 , self.frame.size.width / 3, 30);
    _imagePage.center = CGPointMake(self.frame.size.width / 2, self.frame.size.height - 30 / 2);
    }





//当挺止减速
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
#warning 直接判断与0相等有何问题
    if (scrollView.contentOffset.x == 0) {
        
//        [_cycleCollectionView setContentOffset:CGPointMake(_cycleCollectionView.bounds.size.width * (_array.count - 2), 0)];
        
        //滚动到对应下标位置
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_array.count - 2  inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        
    }
    else if(scrollView.contentOffset.x == _cycleCollectionView.bounds.size.width * (_array.count - 1)){
    
//        [_cycleCollectionView setContentOffset:CGPointMake(_cycleCollectionView.bounds.size.width, 0)];
        
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
#warning 定时器
//    NSTimer
    

}
//更新数据
- (void)setArray:(NSArray *)array{

    _array = array;
    [_cycleCollectionView reloadData];

}

@end

#warning 扩展
//1.加label
//2.定时器
//3.pageControl
//4.自定义cell的类型





























#pragma mark - 创建cell



@implementation JHCollectionViewCell

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        _cycleImage = [[UIImageView alloc] initWithFrame:self.bounds];
        _cycleLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, frame.size.width / 3, 44)];
        _cycleLable.center = CGPointMake(frame.size.width / 2, frame.size.height / 3);
        _cycleLable.backgroundColor = [UIColor whiteColor];
        [self.contentView addSubview:_cycleImage];
        [self.contentView addSubview:_cycleLable];
    }
    return self;
}

@end








